package com.team2.cyber_eye.ActivityHelpers;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.team2.cyber_eye.R;
import com.team2.shared.Product;

public class AdapterProduct extends BaseAdapter {
    
    private Activity activity;
    private ArrayList<Product> products;
    private static LayoutInflater inflater=null;
    public ImageLoader imageLoader; 
    
    public AdapterProduct(Activity a, ArrayList<Product> p) {
        activity = a;
        if (p == null)
        	p = new ArrayList<Product>();
        products = p;
        inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        imageLoader=new ImageLoader(activity.getApplicationContext());
    }

    public int getCount() {
    	if(products.size()==0) return 1;
        return products.size();
    }

    public Object getItem(int position) {
    	if (position < 0 || position >= products.size())
    		return null;
    	
        return products.get(position);
    }

    public long getItemId(int position) {
        return position;
    }
    
    public View getView(int position, View convertView, ViewGroup parent) {
        View vi=convertView;
        if(convertView==null)
            vi = inflater.inflate(R.layout.item_product, null);
        if(products.isEmpty()) 
        {
            TextView name=(TextView)vi.findViewById(R.id.name);
            TextView price=(TextView)vi.findViewById(R.id.price);
            ImageView image=(ImageView)vi.findViewById(R.id.image);
            
        	name.setText("Product Not Found");
        	price.setText("");
        	imageLoader.DisplayImage("http://a3.twimg.com/profile_images/670625317/aam-logo-v3-twitter.png", image);
        }
        else
        {
        	Product prod = products.get(position);
            TextView name=(TextView)vi.findViewById(R.id.name);
            TextView price=(TextView)vi.findViewById(R.id.price);
            ImageView image=(ImageView)vi.findViewById(R.id.image);
            
            name.setText(prod.getTitle());
            
            if(prod.getPrice() == null || prod.getPrice().equals(" ")){
            	price.setVisibility(View.GONE);
            }else{
            	price.setText(prod.getPrice());
            }
            
            imageLoader.DisplayImage(prod.getImageLink(), image);        	
        }
        return vi;
    }
}
